package com.all.bll;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import android.content.Context;
import com.all.dao.DatabaseHelper;
import com.android.AppManager;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;


public class NatBLLUtils<T> {
	public static NatBLLUtils<?> NatObjectBLL=null;
	public Class<?> cls = null;
	private DatabaseHelper databaseHelper;
	private Context mContext;
	public Dao<T, Integer> objDao;
	/**
	 * ����ģʽ
	 * */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static NatBLLUtils<?> getInstance(Class<?> cls) {
		if (NatObjectBLL == null) {
			synchronized (NatBLLUtils.class) { // 1
				NatBLLUtils<?> temp = NatObjectBLL; // 2
				if (temp == null) {
					synchronized (NatBLLUtils.class) { // 3
						temp = new NatBLLUtils(AppManager.getAppManager()
								.currentActivity(),cls); // 4
					}
					NatObjectBLL = temp; // 5
				}
			}
		}
		return NatObjectBLL;
	}
	
	public NatBLLUtils(Context context,Class<?> cls)
	{
		this.mContext = context;
		this.cls =cls;
		try {
			getDao();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//this.entity = entity;
	}
	public DatabaseHelper getHelper()
	{
		if (databaseHelper == null) {
			databaseHelper = OpenHelperManager.getHelper(mContext,
					DatabaseHelper.class);
		}
		return databaseHelper;
	}
	
	public Dao<T, Integer> getDao() throws SQLException 
	{
		if(objDao==null)
		{
			objDao = getHelper().getDao(cls);  
		}
		return objDao;
		
	}
	public void close()
	{
		if(databaseHelper!=null)
			OpenHelperManager.releaseHelper();
			objDao = null;
			NatObjectBLL = null;
			databaseHelper= null;
	}
	
	public int addObject(T obj)
	{
		int num = 0;
		try {
			num = objDao.create(obj);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return num;
	}
	
	 public void createObject(T obj)
	    {
	    	 try {
	    		 objDao.createOrUpdate(obj);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
	 
	 public T createIfNotExists(T entity)
		{
			try {
				return objDao.createIfNotExists(entity);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
	@SuppressWarnings({ "hiding", "unchecked" })
	public <T> T queryForId(int id)
	{
		T entity = null;
		try {
			entity = (T) objDao.queryForId(id);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return entity;	
	}
	
	public List<T> queryForEntity(T entity)
	{
		try {
			return objDao.queryForMatching(entity);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;	
	}
	public List<T> queryForEq(String column,Object val)
	{
		List<T> objlist=null;
		
		try {
			objlist = objDao.queryForEq(column, val);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return objlist;	
	}
	
	public List<T> queryForFieldValues(Map<java.lang.String,java.lang.Object> fieldValues)
	{
		List<T> objlist=null;
		try {
			objlist = objDao.queryForFieldValues(fieldValues);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return objlist;	
	}
	//���ID�������ݽ���ɾ��
	public int  deleteObject(int ID)
	{
		int num = 0;
		try {
			num=objDao.deleteById(ID);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return num;
	}
	//��ݴ���Ķ������ݽ���ɾ��
	public int  deleteObject(T object)
	{
		int num = 0;
		try {
			num=objDao.delete(object);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return num;
	}
	
	//����Ҫ����ɾ���������?����ݽ�������ɾ��
	 public int deleteObject(List<T> lst) {  
		 int num = 0;
			try {
				num= objDao.delete(lst);  
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return num;
	    }
	 //���ĳ������ֶζ���ݿ���ݽ���ɾ�����ɾ��SQL�������where�Ӿ�
	 public int deleteObject(java.lang.String str,java.lang.Object val){  
		 List<T> lst = queryForEq(str,val);  
		 if (null != lst && !lst.isEmpty()) {  
			 return deleteObject(lst);  
		 }  
		 return 0;  
	 }  
	 //���û�������ݶ�������������ж�Ҫɾ�����ݣ�Ȼ�����ɾ�����ɾ��SQL����Ķ��where�Ӿ�
	 public int deleteObject(Map<java.lang.String,java.lang.Object> fieldValues){  
		 List<T> lst = queryForFieldValues(fieldValues);  
		 if (null != lst && !lst.isEmpty()) {  
			 return deleteObject(lst);  
		 }  
		 return 0;  
	 }  
	 /**
     * ɾ��ȫ��
	 * @throws SQLException 
     */
    public int deleteAll() throws SQLException
    {
    	int num = 0;
    	num  = objDao.delete(queryAll());
    	
    	return num;
    }

    /**
     * ��ѯ���е�
     * @throws SQLException 
     */
    public List<T> queryAll()
    {
        List<T> objlist = null;
		try {
			objlist = objDao.queryForAll();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return objlist;
    }
    
    /**
     * ����
     * 
     * @param obj ����µ�obj
     * @throws SQLException 
     */
    public int update(T obj) 
    {
    	int i = 0;
    	try {
			i = objDao.update(obj);
			
			return i;
					
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        // mUserDAO.update(user);
    	return i;
    }
    
    /**
     * @param pagenum ��ѯ�ĵڼ���ҳ��
     * @param pagecount ÿ��ҳ����ʾ���������
     * @throws SQLException 
     */
    @SuppressWarnings("deprecation")
	public List<T> queryPageData(int pagenum,int pagecount)
    {
    	 QueryBuilder<T, Integer> builder = objDao.queryBuilder();
    	 builder.limit(pagenum*pagecount);
    	 PreparedQuery<T> query;
    	 List<T> objlist = null;
		try {
			query = builder.prepare();
		    objlist = objDao.query(query);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	 
    	 return objlist;
        // mUserDAO.update(user);
    }
    
    public int getTotalPageCount()
    { 
    	int num=0;
    	try {
			 num = objDao.queryForAll().size();
			 
			 return num;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return num;
    }


	/**
	* @Title: queryData
	* @Description: TODO(��������ģ�����ģ��Ļ�ϲ�ѯ)
	* @param @param pagenum ҳ��
	* @param @param pagecount ҳ������
	* @param @param map ��Ų�ѯ������
	* @param @return    �趨�ļ�
	* @return List<T>    ��������
	* @throws
	*/ 
	@SuppressWarnings("deprecation")
	public List<T> queryData(int pagenum, int pagecount,
			Map<String, String> map) {
		// TODO Auto-generated method stub
		 QueryBuilder<T, Integer> builder = objDao.queryBuilder();
		 Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
		 Where<T, Integer> where = null;
		 //�ж��Ƿ�¼���ѯ���������¼����ʵ��where�־�
		 if(it.hasNext())
		 {
			 System.out.println("this is");
			 where= builder.where();
		 }
		//�����ѯ����
		 while(it.hasNext())
		 {
			 
			 Map.Entry<String, String> entry = it.next();
			 try {
				 //ʵ��where�Ӿ�
				 if(!entry.getValue().startsWith("%"))
				 {
					 where.eq(entry.getKey(),entry.getValue());
				 }else
				 {
					 where.like(entry.getKey(),entry.getValue());
				 }
				if(it.hasNext())
				where.and();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
    	 builder.limit(pagenum*pagecount);
    	 PreparedQuery<T> query;
    	 List<T> objlist = null;
		try {
			query = builder.prepare();
		    objlist = objDao.query(query);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	 
    	 return objlist;
	}
	

	/**
	* @Title: queryLike
	* @Description: TODO(����ģ���ѯ)
	* @param @param pagenum ��ҳ��ʾ��ҳ��
	* @param @param pagecount �ֲ���ʾ������
	* @param @param map ģ���ѯ������
	* @param @return    �趨�ļ�
	* @return List<T>    ��������
	* @throws
	*/ 
	@SuppressWarnings("deprecation")
	public List<T> queryLike(int pagenum, int pagecount,
			Map<String, String> map) {
		// TODO Auto-generated method stub
		 QueryBuilder<T, Integer> builder = objDao.queryBuilder();
		 Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
		 Where<T, Integer> where = null;
		 //�ж��Ƿ�¼���ѯ���������¼����ʵ��where�־�
		 if(it.hasNext())
		 {
			 System.out.println("this is");
			 where= builder.where();
		 }
		//�����ѯ����
		 while(it.hasNext())
		 {
			 
			 Map.Entry<String, String> entry = it.next();
			 try {
				 //ʵ��where�Ӿ�
				//where.eq(entry.getKey(),entry.getValue());
				 where.like(entry.getKey(),"%"+entry.getValue()+"%");
				if(it.hasNext())
				where.and();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
    	 builder.limit(pagenum*pagecount);
    	 PreparedQuery<T> query;
    	 List<T> objlist = null;
		try {
			query = builder.prepare();
		    objlist = objDao.query(query);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	 
    	 return objlist;
	}

   
}
